<template>
  <div class="app-container">

    <el-card class="box-card">
      <h3>配方信息</h3>
      <el-form ref="formula" :rules="rule1s" :model="formula" label-width="150px">
        <el-form-item label="配方编码" prop="code">
          <el-input v-model="formula.code" />
        </el-form-item>
        <el-form-item label="配方名称" prop="name">
          <el-input v-model="formula.name" />
        </el-form-item>
        <el-form-item label="配方包含的商品个数" prop="number">
          <el-input v-model="formula.number" placeholder="件 / 个 / 盒" />
        </el-form-item>
        <el-form-item label="配方简介" prop="brief">
          <el-input v-model="formula.brief" />
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="box-card">
      <h3>原料参数</h3>
      <el-button type="primary" @click="handleAttributeShow">添加</el-button>
      <el-table :data="attributes">
        <el-table-column property="materialId" label="原料ID" />
        <el-table-column property="materialName" label="原料名称" />
        <el-table-column property="amount" label="原料数量" />
        <el-table-column property="unit" label="单位" />
        <el-table-column align="center" label="操作" width="100" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button type="danger" size="mini" @click="handleAttributeDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog :visible.sync="attributeVisiable" title="添加原料">
        <el-form
          ref="attributeForm"
          :model="attributeForm"
          :rules="rule2s"
          status-icon
          label-position="left"
          label-width="100px"
          style="width: 400px; margin-left:50px;"
        >
          <el-form-item label="原料名称" prop="materialId">
            <el-select v-model="attributeForm.materialId" @change="materialChange" filterable placeholder="请输入关键词">
              <el-option
                v-for="item in materialList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
<!--            <el-select-->
<!--              v-model="attributeForm.materialId"-->
<!--              filterable-->
<!--              remote-->
<!--              placeholder="请输入关键词"-->
<!--              :remote-method="remoteMethod"-->
<!--              :loading="loading"-->
<!--              @change="materialChange"-->
<!--            >-->
<!--              <el-option-->
<!--                v-for="item in materialList"-->
<!--                :key="item.id"-->
<!--                :label="item.name"-->
<!--                :value="item.id"-->
<!--              />-->
<!--            </el-select>-->
          </el-form-item>
          <el-form-item label="原料数量" prop="amount">
            <el-input type="number" v-model="attributeForm.amount" placeholder="0.00000000">
              <template slot="append">{{ unit }}</template>
            </el-input>
          </el-form-item>
          <el-form-item prop="name" hidden="true">
            <span v-model="attributeForm.materialName" />
          </el-form-item>
          <el-form-item prop="unit" hidden="true">
            <span v-model="attributeForm.unit" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="attributeVisiable = false">取消</el-button>
          <el-button type="primary" @click="handleAttributeAdd">确定</el-button>
        </div>
      </el-dialog>
    </el-card>

    <div class="op-container">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handlePublish">创建</el-button>
    </div>

  </div>
</template>

<style>
  .el-card {
    margin-bottom: 10px;
  }
  .el-tag + .el-tag {
    margin-left: 10px;
  }

  .op-container {
    display: flex;
    justify-content: center;
  }
</style>

<script>
import { createFormula } from '@/api/formula'
import { searchMaterial,listMaterial } from '@/api/material'
import Editor from '@tinymce/tinymce-vue'
import { MessageBox } from 'element-ui'
import { getToken } from '@/utils/auth'

export default {
  name: 'FormulaCreate',
  components: { Editor },

  data() {
    return {
      unit: 'Kg',
      materialList: [],
      materialId: undefined,
      loading: false,
      formula: { name: '', number: 1, brief: '' },
      attributeVisiable: false,
      attributeForm: { materialId: undefined, amount: '', materialName: '', unit: '' },
      attributes: [],
      listQuery: {
        page: 1,
        limit: 10000,
        name: undefined,
        sort: 'add_time',
        order: 'desc'
      },
      rule1s: {
        code: [{ required: true, message: '配方编码不能为空', trigger: 'blur' }],
        name: [{ required: true, message: '配方名称不能为空', trigger: 'blur' }]
      },
      rule2s: {
        materialId: [{ required: true, message: '原料名称不能为空', trigger: 'blur' }],
        amount: [{ required: true, message: '原料数量不能为空', trigger: 'blur' }],
      }
    }
  },
  computed: {
    headers() {
      return {
        'X-Litemall-Admin-Token': getToken()
      }
    }
  },
  created() {
    this.getMaterialList()
  },

  methods: {
    getMaterialList() {
      listMaterial(this.listQuery)
        .then(response => {
          this.materialList = response.data.data.list
        })
        .catch(() => {
          this.materialList = []
        })
    },
    handleCancel: function() {
      this.$store.dispatch('tagsView/delView', this.$route)
      this.$router.push({ path: '/stuff/formula' })
    },
    handlePublish: function() {
      this.$refs['formula'].validate(valid => {
        if(valid) {
          const finalFormulas = {
            formula: this.formula,
            attributes: this.attributes
          }
          createFormula(finalFormulas).then(response => {
            this.$notify.success({
              title: '成功',
              message: '创建成功'
            })
            this.$store.dispatch('tagsView/delView', this.$route)
            this.$router.push({ path: '/stuff/formula' })
          }).catch(response => {
            MessageBox.alert('业务错误：' + response.data.errmsg, '警告', {
              confirmButtonText: '确定',
              type: 'error'
            })
          })
        }
      })
    },
    handleAttributeShow() {
      this.attributeForm = {}
      this.attributeVisiable = true
    },
    handleAttributeAdd() {
      this.$refs['attributeForm'].validate(valid => {
        if(valid){
          this.attributes.unshift(this.attributeForm)
          this.attributeVisiable = false
        }
      })
    },
    handleAttributeDelete(row) {
      const index = this.attributes.indexOf(row)
      this.attributes.splice(index, 1)
    },
    remoteMethod(query) {
      if (query !== '') {
        this.loading = true
        const params = {
          keyword: query
        }
        searchMaterial(params)
          .then(response => {
            this.materialList = response.data.data
            this.loading = false
          })
          .catch(() => {
            this.materialList = []
            this.loading = false
          })
      } else {
        this.materialList = []
      }
    },
    materialChange(id) {
      const items = this.materialList.forEach(item => {
        if (item.id === id) {
          this.unit = item.unit
          this.attributeForm.materialName = item.name
          this.attributeForm.unit = item.unit
        }
      })
    }
  }
}
</script>
